<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
       size="small"
    >
      <el-form-item label="园区编号" prop="parkId">
        <el-select clearable
                   v-model="queryParams.parkId"
                   placeholder="请选择园区"
        >
          <el-option
            v-for="item in parkList"
            :key="item.id"
            :label="item.parkNum"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!--<el-form-item label="仪表类型" prop="meterType">-->
       <!--<el-select-->
            <!--clearable-->
            <!--v-model="queryParams.meterType"-->
            <!--placeholder="请选择仪表类型"-->
          <!--&gt;-->
            <!--<el-option-->
              <!--v-for="item in meterTypeList"-->
              <!--:key="item.dictValue"-->
              <!--:label="item.dictLabel"-->
              <!--:value="item.dictValue"-->
            <!--&gt;-->
            <!--</el-option>-->
          <!--</el-select>-->
        <!--</el-select>-->
      <!--</el-form-item>-->
      <el-form-item label="仪表名称" prop="meterName">
        <el-input
          v-model="queryParams.meterName"
          placeholder="请输入仪表名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="企业名称" prop="enterpriseName">
        <el-input
          v-model="queryParams.enterpriseName"
          placeholder="请输入企业名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="仪表状态" prop="state">
         <el-select
            clearable
            v-model="queryParams.state"
            placeholder="请选择仪表状态"
          >
            <el-option
              v-for="item in workState"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['energy:nyMeterAccount:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['energy:nyMeterAccount:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['energy:nyMeterAccount:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['energy:nyMeterAccount:edit']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['energy:nyMeterAccount:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="nyMeterAccountList" @selection-change="handleSelectionChange"
              row-key="id"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="编号" align="center" key="id" prop="id"  />-->
      <el-table-column label="仪表编码" align="center" prop="meterNum"/>
      <!--<el-table-column label="表计编号" align="center" prop="meterCode"/>-->
      <el-table-column label="仪表名称" align="center" prop="meterName"/>
      <!--<el-table-column label="设备分类" align="center" prop="deviceType" />-->
      <!--<el-table-column label="仪表类型" align="center" prop="meterTypeNew" />-->
      <el-table-column label="类别" align="center" prop="categoryNew"/>
      <el-table-column label="初始读数" align="center" prop="initialValue" />
      <el-table-column label="当前读数" align="center" prop="currentValue" />
      <el-table-column label="分摊池初始值" align="center" prop="shareInitialValue"/>
      <el-table-column label="园区" align="center" prop="parkNum" />
      <el-table-column label="楼栋" align="center" prop="buildingNum" />
      <el-table-column label="安装位置" align="center" prop="installPosition" />
      <el-table-column label="仪表型号" align="center" prop="meterModel" />
      <el-table-column label="生产厂商" align="center" prop="supplier" />
      <el-table-column label="设备状态" align="center" prop="stateNew" />
      <!--<el-table-column label="倍率" align="center" prop="magnification" />-->
      <el-table-column label="企业名称" align="center" prop="enterpriseName" />
      <el-table-column label="用途" align="center" prop="use1"/>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['energy:nyMeterAccount:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['energy:nyMeterAccount:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仪台账对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form
        ref="form"
        size="small"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="仪表编码" v-if="form.id" prop="meterNum">
          <el-input v-model="form.meterNum" placeholder="请输入仪表编码" disabled/>
        </el-form-item>
        <el-form-item label="仪表名称" prop="meterName">
          <el-input v-model="form.meterName" placeholder="请输入仪表名称"/>
        </el-form-item>
        <!--<el-form-item label="表计编号" prop="meterCode">-->
          <!--<el-input v-model="form.meterCode" placeholder="请输入表计编号"/>-->
        <!--</el-form-item>-->
        <el-form-item label="设备分类" v-if="!form.id">
          <treeselect v-model="form.sysBmId" :options="sysBmTypeOptions" :normalizer="bmNormalizer"
                      @select="genCode" placeholder="选择设备分类" :disabled="disabled"/>
        </el-form-item>
        <el-form-item label="父级" prop="parentId">
          <treeselect v-model="form.parentId" :options="nyOptionList" :normalizer="normalizer" @select="handleParentChange"
                      placeholder="请选择父级"/>
        </el-form-item>
        <!--<el-form-item label="仪表类型" prop="meterType">-->
          <!--<el-select-->
            <!--clearable-->
            <!--v-model="form.meterType"-->
            <!--placeholder="请选择仪表类型"-->
          <!--&gt;-->
            <!--<el-option-->
              <!--v-for="item in meterTypeList"-->
              <!--:key="item.dictValue"-->
              <!--:label="item.dictLabel"-->
              <!--:value="item.dictValue"-->
            <!--&gt;-->
            <!--</el-option>-->
          <!--</el-select>-->
        <!--</el-form-item>-->
        <el-form-item label="仪表类别" prop="category">
          <el-select clearable v-model="form.category"
            placeholder="请选择仪表类别">
            <el-option
              v-for="item in categoryOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="倍率" prop="magnification"  v-show="form.meterType != '0'">-->
          <!--<el-input v-model="form.magnification" type="number" placeholder="请输入倍率" />-->
        <!--</el-form-item>-->
        <el-form-item label="初始读数" prop="initialValue">
          <el-input v-model="form.initialValue" type="number" placeholder="请输入初始读数" />
        </el-form-item>
        <el-form-item label="分摊池值"  prop="shareInitialValue">
          <el-input v-model="form.shareInitialValue" type="number" placeholder="请输入分摊池初始值"
          />
        </el-form-item>
        <el-form-item label="园区" prop="parkNum">
          <el-select v-model="form.parkNum" placeholder="请选择园区" @change="selectPark(form.parkNum)">
            <el-option
              v-for="item in parkList"
              :key="item.id"
              :label="item.parkNum"
              :value="item.parkNum"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="楼栋" prop="buildingNum">
          <el-select v-model="form.buildingNum" placeholder="请选择楼栋">
            <el-option
              v-for="item in buildingList"
              :key="item.id"
              :label="item.buildingNum"
              :value="item.buildingNum"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="安装位置" prop="installPosition">
          <el-input v-model="form.installPosition" placeholder="请输入安装位置"/>
        </el-form-item>
        <el-form-item label="仪表型号" prop="meterModel">
          <el-input v-model="form.meterModel" placeholder="请输入仪表型号" />
        </el-form-item>
        <el-form-item label="生产厂商" prop="supplier">
          <el-select v-model="form.supplier" filterable placeholder="请选择生产厂商">
            <el-option
              v-for="item in supplierList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仪表状态" prop="state">
          <el-select
            clearable
            v-model="form.state"
            placeholder="请选择仪表状态"
          >
            <el-option
              v-for="item in workState"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="企业" prop="enterpriseId">
          <el-select v-model="form.enterpriseId" filterable
            placeholder="请选择企业"
            size="small"
          >
            <el-option
              v-for="item in qyEnterpriseList"
              :key="item.id"
              :label="item.enterpriseName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用途" prop="use1">
          <el-select clearable v-model="form.use1" placeholder="请选择仪表用途">
            <el-option
              v-for="item in meterUseTypeList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 抄表导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?meterType=' + upload.meterType"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!--<el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据-->
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listNyMeterAccount,
  getNyMeterAccount,
  delNyMeterAccount,
  addNyMeterAccount,
  updateNyMeterAccount,
} from "@/api/smartParks/energy/energyMeterSummaryTable";
import { listData } from "@/api/system/dict/data"; //字典接口
import {listBuiPark} from "@/api/parkAssets/enterCommunity";
import {listBuiBuilding} from "@/api/parkAssets/building";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listQyEnterprise} from "@/api/smartParks/merchants/merchantsCompanySettlein";
import { listWySupplier} from "@/api/smartParks/wySupplier/wySupplier";
import { getToken } from "@/utils/auth";

export default {
  name: "NyMeterAccount",
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仪台账表格数据
      nyMeterAccountList: [],
      qyEnterpriseList: [],
      nyOptionList: [],
      supplierList:[],
      sysBmTypeOptions:this.$store.state.permission.sysBmTree,
      // 弹出层标题
      title: "",
      disabled:false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 500,
        parkId: null,
        meterType: '水表',
        meterNum: null,
        meterName: null,
        meterModel: null,
        installPosition: null,
        state: null,
        magnification: null,
        initialValue: null,
        enterpriseName: null,
        parentId: null,
        tenantId: null,
        category: null,
        use1: null,
      },
      // 表单参数
      form: {},
      // 用户导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        meterType: '水表',
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/energy/nyMeterAccount/importData"
      },
      meterTypeList: [],
      meterUseTypeList: [],
      workState: [],
      parkList: [],
      categoryOptions:[],
      buildingList: [],
      // 表单校验
      rules: {
        category:[{required: true,message: "仪表类别不能为空", trigger: "change",}],
        // meterType: [
        //   {
        //     required: true,
        //     message: "仪表类型不能为空",
        //     trigger: "change",
        //   },
        // ],
        meterName:[{required: true,message: "名称不能为空", trigger: "change",}],
        parkNum:[{required: true,message: "园区不能为空", trigger: "change",}],
        // magnification:[{required: true,message: "仪表倍率不能为空", trigger: "change",}],
        initialValue:[{required: true,message: "仪表初始值不能为空", trigger: "change",}],
        shareInitialValue:[{required: true,message: "分摊池不能为空", trigger: "change",}],

      },
    };
  },
  created() {
    this.getList();
    this.getListFirst();
    this.getParkList();
  },
  methods: {
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "抄表导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('energy/nyMeterAccount/importTemplate',{
        ...this.queryParams
      }, `水表导入模板.xlsx`)
    },
    genCode(item){
      this.form.sysBmId=item.bmId
    },
    getListFirst() {
      listData({ dictType: "meter_type" }).then((response) => {
        this.meterTypeList = response.rows;
      });
      listData({ dictType: "mater_use_type" }).then((response) => {
        this.meterUseTypeList = response.rows;
      });
      listData({ dictType: "device_work_state" }).then((response) => {
        this.workState = response.rows;
      });
      this.getDicts("meter_category").then(response => {
        this.categoryOptions = response.data;
      });
      listQyEnterprise().then((response) => {
        this.qyEnterpriseList = response.rows;
      });
      listWySupplier().then((response) => {
        this.supplierList = response.rows;
      })
    },
    getParkList(){
      //查询园区列表，赋值给parkList;
      listBuiPark().then((response) =>{
        this.parkList = response.rows;
      })
    },
    handleParentChange(node, instanceId){
      //this.form.category = String(parseInt(node.category) +1);
      this.form.meterType = node.meterType;
    },
    selectPark(value){
      //buildingList,parkList
      //this.form.buildingNum = "";
      this.$set(this.form, "buildingNum", "");
      this.buildingList=[];
      listBuiBuilding({ parkNum: value }).then((response) =>{
        this.buildingList = response.rows;
      })
    },
    /** 查询仪台账列表 */
    async getList() {
      this.loading = true;
      await this.getListFirst();
      listNyMeterAccount(this.queryParams).then((response) => {
        response.rows.forEach((item) => {
          this.meterTypeList.forEach((itemType) => {
            if (itemType.dictValue === item.meterType) {
              item.meterTypeNew = itemType.dictLabel;
            }
          });
          item.categoryNew = this.selectDictLabel(this.categoryOptions, item.category);
          this.workState.forEach((itemType) => {
            if (itemType.dictValue === item.state) {
              item.stateNew = itemType.dictLabel;
            }
          });
        });
        this.nyMeterAccountList = this.handleTree(response.rows, "id","parentId");
        this.nyOptionList=JSON.parse(JSON.stringify(this.nyMeterAccountList));
        this.total = response.total;
        this.loading = false;
      });

    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.meterNum,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        meterType: '水表',
        meterNum: null,
        meterName: null,
        meterModel: null,
        supplier:null,
        installPosition: null,
        state: null,
        magnification: null,
        initialValue: null,
        shareInitialValue: null,
        enterpriseName: null,
        parentId: null,
        category: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    optionTree(treeList,lv){
      if (this.isEmpty(treeList)){
        return
      }
      treeList.forEach((item,index)=>{
        if (lv==2){
          item.children=[]
        }else if (!this.isEmpty(item.children)){
          this.optionTree(item.children,lv+1)
        }
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    //选择表编码后，当前度数与抄表日期显示
    handleMeterNumChange(meterNum){
      //let id = selection.map(item => item.id)
      let obj = {};
      obj = this.meterList.find((item)=>{
        return item.id === meterNum;
      });
      this.form.lastValue = obj.currentValue;
      this.form.lastCheckDate = obj.updateTime;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加水表台账";
      this.disabled = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getNyMeterAccount(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改水表台账";
        this.disabled = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if(this.form.enterpriseId != null){
            this.form.enterpriseName = this.qyEnterpriseList.filter((item) =>
              item.id == this.form.enterpriseId)[0].enterpriseName;
          }
          if (this.form.id != null) {
            updateNyMeterAccount(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNyMeterAccount(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除仪台账的数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(function () {
          return delNyMeterAccount(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "energy/nyMeterAccount/export",
        {
          ...this.queryParams,
        },
        `energy_nyMeterAccount.xlsx`
      );
    },
  },
};
</script>

<style>
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type="number"]{
    -moz-appearance: textfield;
  }
</style>
